/**
 * 游戏类，作为中介者，统领所有的类
 */
(function(){
	class Game {
		constructor(params){
			//每秒走多少帧的动画
			this.fps = params.fps || 60;

			//获取画布canvas
			this.canvas = document.getElementById(params.canvasId || 'canvas');

			//获取上下文
			this.ctx = this.canvas.getContext('2d');

			//定时器
			this.timer = null;

			//图片资源
			this.images = null;

			//帧工具，负责更新帧率和帧编号
			this.frameUtil = new FrameUtil();

			//静态资源管理器
			this.sr = new StaticResourcesUtil();
			this.sr.loadImages('/r.json',(alreadyLoadNum,total,images)=>{
				this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
				this.ctx.font="20px 微软雅黑";
				this.ctx.fillText(`正在加载游戏资源${alreadyLoadNum}/${total}...`,10,80);
				if(alreadyLoadNum==total){
					this.images = images;
					this.run();
				}
			})
		}

		//开始游戏
		run(){
			clearInterval(this.timer);
			this.timer = setInterval(()=>{
				this.mainloop();
			},1000/this.fps);


			this.fangzi = new Background({
				image:this.images.fangzi,
				width:300,
				height:256,
				speed:1,
				y:140
			})

			this.shu = new Background({
				image:this.images.shu,
				width:300,
				height:216,
				speed:2,
				y:240
			})

			this.diban = new Background({
				image:this.images.diban,
				width:48,
				height:48,
				speed:2.6,
				y:this.canvas.height - 48
			});

			this.bird = new Bird();
		}

		//主循环
		mainloop(){
			//清除画布
			this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);
			this.frameUtil.update();
			//渲染帧率和帧编号
			this.ctx.font = "16px Consolas";
			this.ctx.fillText('FPS / ' + this.frameUtil.realFps,10,20);
			this.ctx.fillText('FNO / ' + this.frameUtil.currentFrame,10,40);

			//渲染背景
			this.fangzi.update();
			this.fangzi.render();

			this.shu.update();
			this.shu.render();

			this.diban.update();
			this.diban.render();

			this.bird.update();
			this.bird.render();
		}

		//暂停游戏
		pause(){
			clearInterval(this.timer);
		}

	}

	window.Game = Game;
})();

